/**
 * 
 */
package com.pactera.android.service;

import com.pactera.android.application.PacteraApplication;

import android.app.Service;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.IBinder;
import android.util.Log;

/**
 * @author David Zheng
 *
 */
public class NotificationService extends Service {
	
	static final String TAG = "NotificationService";
	
	static final int DELAY = 600000;
	
	private Puller puller;
	
	private PacteraApplication app;

	/* (non-Javadoc)
	 * @see android.app.Service#onBind(android.content.Intent)
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	/* (non-Javadoc)
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		this.app = (PacteraApplication)getApplication();
		this.puller = new Puller();
		Log.d(TAG, "onCreate");
	}
	
	/* (non-Javadoc)
	 * @see android.app.Service#onStartCommand(android.content.Intent, int, int)
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		boolean isNetworkDown = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
		if (!isNetworkDown && puller.getState() == Thread.State.NEW) {
			this.puller.start();
			this.app.setNotificationServiceRunning(true);
		}
						
		Log.d(TAG, "OnStartCommand: " + isNetworkDown);		
		return START_STICKY; 		
	}
	

	/* (non-Javadoc)
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
		this.puller.interrupt();
		this.puller = null;
		this.app.setNotificationServiceRunning(false);
		Log.d(TAG, "onDestroy");
	}
	
	
	private class Puller extends Thread {
		
		public Puller() {
			super("Pactera-NotificationService");
		}

		/* (non-Javadoc)
		 * @see java.lang.Thread#run()
		 */
		@Override
		public void run() {
			NotificationService service = NotificationService.this;
			while(service.app.isNotificationServiceRunning()) {
				try {
					//connect to server to pull down data
					Log.d(TAG, "Thread Running");
					Thread.sleep(DELAY);
				} catch (InterruptedException e) {
					service.app.setNotificationServiceRunning(false);
				}
			}
		}
		
		
	}


}
